﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;

namespace KWT.DRG_DIP.API.Infrastructure
{
    public class OutputResult : IActionResult
    {
        /// <summary>
        /// 标识
        /// </summary>
        public bool Flag { get; set; }
        /// <summary>
        /// 成功的消息
        /// </summary>
        public string Succ { get; set; }
        /// <summary>
        /// 失败的消息
        /// </summary>
        public string Fail { get; set; }
        /// <summary>
        /// 标识码
        /// </summary>
        public int Code { get; set; }
        /// <summary>
        /// 数据
        /// </summary>
        public object Data { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_flag">标识</param>
        /// <param name="_succ">成功的消息</param>
        /// <param name="_fail">失败的消息</param>
        /// <param name="_code">标识码</param>
        /// <param name="data">数据</param>
        public OutputResult(bool _flag, string _succ = "", string _fail = "", object? data = null, int _code = -1)
        {
            Succ = _succ;
            Fail = _fail;
            Flag = _flag;
            Code = _flag ? 0 : _code;
            Data = data;
        }

        public Task ExecuteResultAsync(ActionContext context)
        {
            var fmt = new IsoDateTimeConverter()
            {
                DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
            };
            var setting = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Converters = new List<JsonConverter> { fmt }
            };
            string msg = Flag ? Succ : Fail;
            string json = JsonConvert.SerializeObject(new { Flag, msg, Code, Data, trace_id = context.HttpContext.TraceIdentifier }, setting);
            context.HttpContext.Response.ContentType = "application/json;charset=utf-8";
            return context.HttpContext.Response.WriteAsync(json);
        }
    }
}
